import { getMenuListByUserId, selectMenuAllApi } from '@/api'
import { MenuState } from '@/interfaces/api/menu'
import store from '@/store'
import { addItem, NMenuColmenu } from '@/utils/tools'
import { ArchiveSharp } from '@vicons/ionicons5'
import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'

const routes: Array<RouteRecordRaw> = [
  {
    path: '/login',
    name: 'login',
    component: () => import('vv/login/index.vue'),
  },
  {
    path: '/',
    name: 'index',
    redirect: '/layout',
  },
  {
    path: '/layout',
    name: 'layout',
    component: () => import('vv/leyout/index.vue'),
  },
]

const router = createRouter({
  history: createWebHistory(),
  routes,
})

router.beforeEach(async (to, from, next) => {
  if (store.state.isok) {
    store.commit('startLoading')
    next()
  } else {
    const res = await selectMenuAllApi({ menuName: '', title: '' })
    if (res.data.data.length === 0) {
      store.commit('setIsOk', true)
      next('/login')
    }

    res.data.data.forEach((item) => addItem(item as any))
    store.commit(
      'setMenuList',
      NMenuColmenu({ label: 'title', key: 'menuName', data: res.data.data as any })
    )
    store.commit('setIsOk', true)
    next({ ...to, replace: true })
  }
})

router.afterEach((to) => {
  store.commit('endLoading')
  if (to.name !== 'login' && to.name !== 'index' && to.name !== 'layout') {
    store.commit('setLinkList', {
      label: to.meta.title,
      key: to.name,
      type: 'success',
    })
  }
})

export default router
